from flask import render_template, current_app, jsonify, g, request

from info import constants, db
from info.models import News, Comment, CommentLike
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import news_blu


@news_blu.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):
    # 1.组织数据
    user = g.user
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")
    news.clicks += 1
    is_collected = False
    if user:
        if news in user.collection_news:
            is_collected = True
    news_list = []

    try:
        news_li = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")
    for new in news_li:
        news_list.append(new.to_dict())

    # 2.组织评论数据
    comments_list = []
    try:
        comments_list = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")

    # 当前用户点赞条数
    comments_id = [comment.id for comment in comments_list]
    comments_like = CommentLike.query.filter(CommentLike.comment_id.in_(comments_id), CommentLike.user_id == user.id)
    comment_like_id = [comment_like.id for comment_like in comments_like]
    comment_dict_li = []
    for comments in comments_list:
        comment = comments.to_dict
        comment['is_like'] = False
        if comments.id in comment_like_id:
            comment['is_like'] = True
        comment_dict_li.append(comment)
    data = {
        'news2': news.to_dict(),
        'user': user.to_dict() if user else None,
        'news_dict': news_list,
        'comments': comment_dict_li,
        'is_collected': is_collected
    }

    return render_template('news/detail.html', data=data)


@news_blu.route('/news_collect', methods=["POST"])
@user_login_data
def collect_news():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="先登录")
    news_id = request.json.get('news_id')
    action = request.json.get('action')
    if not all([action, news_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if action not in ['collect', 'cancel_collect']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")
    if action != 'collect':
        if news in user.collection_news:
            user.collection_news.remove(news)
    else:
        if news not in user.collection_news:
            user.collection_news.append(news)
    return jsonify(errno=RET.OK, errmsg="成功")


# 点赞的功能实现
@news_blu.route('/comment_like', methods=["POST"])
@user_login_data
def comment_like():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="请先登录")
    comment_id = request.json.get('comment_id')
    news_id = request.json.get('news_id')
    action = request.json.get('action')
    if not all([comment_id, news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        news_id = int(news_id)
        comment_id = int(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="查询错误")
    if action not in ['add', 'remove']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")
    if action != 'add':
        comment_like = CommentLike.query.filter(CommentLike.comment_id == comment_id, CommentLike.user_id == user.id)
        if comment_like:
            db.session.delete(comment_like)
            comment.like_count -= 1
    else:
        comment_like = CommentLike.query.filter(CommentLike.comment_id == comment_id, CommentLike.user_id == user.id)
        if not comment_like:
            comment_like = CommentLike()
            comment_like.user_id = user.id
            comment_like.comment_id = comment_id
            db.sesssion.add(comment_like)
            comment.like_count += 1
    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="成功")


@news_blu.route('/news_comment', methods=["POST"])
@user_login_data
def news_comment():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="查询错误")
    news_id = request.json.get('news_id')
    comment_content = request.json.get('comment')
    parent_id = request.json.get('parent_id')
    if not all([news_id, comment_content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")
    if not news:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news_id
    comment.content = comment_content
    if parent_id:
        comment.parent_id = parent_id
    try:
        db.session.add(comment)
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
    return jsonify(errno=RET.OK, errmsg="成功", data=comment.to_dict())
